import pygame
import os

class SoundManager:
    def __init__(self):
        # 初始化pygame混音器
        pygame.mixer.init()
        
        # 音效文件路径
        self.sound_path = "sounds"
        
        # 音效字典
        self.sounds = {}
        
        # 背景音乐文件路径
        self.music_path = "sounds"
        
        # 加载音效
        self.load_sounds()
    
    def load_sounds(self):
        # 如果音效目录存在，加载音效文件
        if os.path.exists(self.sound_path):
            for filename in os.listdir(self.sound_path):
                if filename.endswith(".wav") or filename.endswith(".mp3"):
                    sound_name = os.path.splitext(filename)[0]
                    sound_path = os.path.join(self.sound_path, filename)
                    try:
                        self.sounds[sound_name] = pygame.mixer.Sound(sound_path)
                    except pygame.error as e:
                        print(f"无法加载音效文件 {sound_path}: {e}")
        else:
            # 如果音效目录不存在，创建空的音效字典
            self.create_placeholder_sounds()
    
    def create_placeholder_sounds(self):
        # 创建空的音效对象作为占位符
        self.sounds = {
            "attack": None,
            "hit": None,
            "level_up": None,
            "game_over": None,
            "jump": None,
            "victory": None
        }
    
    def play_sound(self, sound_name):
        # 播放音效
        if sound_name in self.sounds and self.sounds[sound_name] is not None:
            # 检查声音是否已经在播放，避免重复播放
            if not self.sounds[sound_name].get_num_channels() or sound_name in ["attack", "jump"]:
                self.sounds[sound_name].play()
    
    def load_music(self, music_file):
        # 加载背景音乐
        music_path = os.path.join(self.music_path, music_file)
        if os.path.exists(music_path):
            try:
                pygame.mixer.music.load(music_path)
            except pygame.error as e:
                print(f"无法加载音乐文件 {music_path}: {e}")
    
    def play_music(self, loops=-1):
        # 播放背景音乐（-1表示循环播放）
        pygame.mixer.music.play(loops)
    
    def stop_music(self):
        # 停止背景音乐
        pygame.mixer.music.stop()
    
    def set_music_volume(self, volume):
        # 设置背景音乐音量（0.0到1.0之间）
        pygame.mixer.music.set_volume(volume)
    
    def set_sound_volume(self, sound_name, volume):
        # 设置特定音效的音量（0.0到1.0之间）
        if sound_name in self.sounds and self.sounds[sound_name] is not None:
            self.sounds[sound_name].set_volume(volume)